import { Component, OnInit, ViewChild } from '@angular/core';

import { Router } from '@angular/router';
import { map } from 'rxjs/internal/operators/map';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { OrganizationSearchComponent } from 'src/app/share/organization-search/organization-search.component';
import { RoleSearchComponent } from 'src/app/share/role-search/role-search.component';
import { zip } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { SetModelPermissionComponent } from 'src/app/share/set-model-permission/set-model-permission.component';
import { SetDataPermissionComponent } from 'src/app/share/set-data-permission/set-data-permission.component';
import {
  RoleService,
  OrganizationService,
  OrganizationRolePK,
  Role,
  OrganizationRoleRelationPK,
  OrganizationRoleRelation
} from 'sparrow-permission-lib';
import { DynamicDataSourceForNzTreeService } from 'src/app/service/dynamic-data-source-for-nz-tree.service';
import { FlatNode } from 'src/app/domain/flat-node';
import { NzTreeCommonService } from 'src/app/service/nz-tree-common.service';
import { NzTreeGetChildren } from 'src/app/service/nz-tree-get-children';
import { NzTreeGetRoleChildrenService } from 'src/app/service/nz-tree-get-role-children.service';

@Component({
  selector: 'app-role',
  templateUrl: './role.component.html',
  styleUrls: ['./role.component.css'],
})
export class RoleComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private orgService: OrganizationService,
    private roleService: RoleService
  ) {}

  dataSource: any;
  hasChild = (_: number, node: FlatNode) => node.expandable;
  treeService: NzTreeCommonService = new NzTreeCommonService();

  ngOnInit(): void {
    let getChildrenService: NzTreeGetChildren =
      new NzTreeGetRoleChildrenService(this.roleService, this.orgService);
    getChildrenService
      .getChildren(
        { id: 'root', label: 'root', level: -1, expandable: true, type: 'ORG' }
      )
      .subscribe(
        (res) => {
          this.dataSource = new DynamicDataSourceForNzTreeService(
            this.treeService.treeControl,
            res,
            getChildrenService
          );
        },
        (error) => {
          this.message.error('初始化失败！' + error);
        }
      );
  }

  // 获取角色详情
  selectedRole!: Role | any;
  onItemSelect(node: FlatNode): void {
    this.treeService.selectListSelection.toggle(node);
    // get the report line
    const parentOrgs$= this.roleService.getParentOrganizations(node.id).pipe(
      switchMap(orgRoles=>zip(...orgRoles.map((orgRole:any)=>this.orgService.get4(orgRole.id.organizationId))))
    )
    const parents$=this.roleService.getParents(node.orgId + '_' + node.id).pipe(
      switchMap((parents:OrganizationRoleRelation[]) =>
        zip(
          ...parents.map((parent) =>
            this.roleService.get3(parent.id?.parentId?.roleId!).pipe(
              map((parentRole:any)=>{return {...parentRole,orgId:parent.id?.parentId?.organizationId}})
            )
          )
        )
      )
    )
    // console.log(node)
    this.roleService
      .get3(node.id)
      .pipe(
        switchMap(role=>parentOrgs$.pipe(
          map(orgs=>{return {...role, parentOrgs: orgs, orgId: node.orgId}})
        )),
        tap((role) => this.selectedRole = role),
        switchMap((role: any) =>
          parents$.pipe(
            map(parents=>{return {...role, parents: parents}})
          )
        ),
        // tap((ss) => console.log(ss)),
      )
      .subscribe((role) => {
        this.selectedRole = role;
      });
  }

  onChange(value: string): void {
    console.log(value);
  }

  setModelPermission() {
    // this.router.navigateByUrl(
    //   this.router.createUrlTree([
    //     '/modelPermission',
    //     { ids: JSON.stringify(this.modelName?.split(',')) },
    //   ])
    // );
  }

  // for new organization

  isNewVisible: boolean = false;
  validateForm!: FormGroup;

  @ViewChild(OrganizationSearchComponent)
  organizationSearch!: OrganizationSearchComponent;

  // 新增岗位
  submitForm() {
    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
          console.log(i);
        }
      }
    } else {
      let role: Role = this.validateForm.value;
      const organizations$: any = this.organizationSearch?.selectedParent.map(
        (p) => p.id
      );

      if (role.id === undefined) {
        this.roleService.create2(role).subscribe((res) => {
          this.isNewVisible = false;
          //更新上级组织
          if (organizations$ != undefined) {
            this.roleService.setParentOrg(res.id!, organizations$).subscribe();
          }
          this.message.success('添加成功！');
          this.isNewVisible = false;
        });
      } else {
        // 更新组织
        let updateRole: any = { ...role };
        updateRole.id = undefined;
        this.roleService.update2(role.id, updateRole).subscribe((res) => {
          this.message.success('更新成功！');
          this.isNewVisible = false;
        });
      }
    }
  }

  addNewOrganization(selectedRole: any) {
    if (selectedRole === null) {
      this.validateForm = this.fb.group({
        name: [null, [Validators.required]],
        code: [null, [Validators.required]],
        // parentId: [null, [Validators.required]],
        // root: [true, [Validators.required]],
      });
    } else {
      this.validateForm = this.fb.group({
        name: [selectedRole.name, [Validators.required]],
        code: [selectedRole.code, [Validators.required]],
        id: [selectedRole.id, [Validators.required]],
      });
    }

    this.isNewVisible = true;
  }

  onClose(): void {
    console.log('tag was closed.');
  }

  isRoleEdit = false;
  showReportRole() {
    this.isRoleEdit = true;
  }

  isRoleReportTree = false;
  showReportRoleTree() {
    this.isRoleReportTree = true;
  }

  @ViewChild(RoleSearchComponent) roleSearch!: RoleSearchComponent;
  saveReportRole(selectedRole: any) {
    let roleRelation: OrganizationRolePK[] = [];
    this.roleSearch.selectedRoles.map((f) => {
      roleRelation.push({
        organizationId: f.orgId,
        roleId: f.id,
      });
    });
    console.log(roleRelation)
    this.roleService
      .addParents(selectedRole.orgId + '_' + selectedRole.id, roleRelation,'response')
      .subscribe((res) => {
        if(res.status===204){
          this.isRoleEdit = false;
          this.message.success('设置上级成功！');
        }
      });
  }

  delRoles() {
    // this.roleService
    //   .deleteBatch(
    //     Array.from(
    //       this.checklistSelection.selected.map((node) => node.id.roleId)
    //     )
    //   )
    //   .subscribe();
  }

  delRole(selectedRole: any) {
    this.roleService.delete1([selectedRole.id], 'response').subscribe((res) => {
      if (res.status === 204) {
        this.message.success('删除成功！');
      } else {
        this.message.error('删除失败，请先移除关联关系！');
      }
    });
  }

  handleCancel() {
    this.isNewVisible = false;
    this.isRoleEdit = false;
    this.isRoleReportTree = false;
  }

  // 取消组织关系，上级
  onTagClose(s: any) {
    console.log(this.selectedRole)
    this.roleService
        .delParents(this.selectedRole.orgId + '_' +this.selectedRole.id, [{organizationId: s.orgId,roleId:s.id}])
        .subscribe((res) => {
          this.message.success('成功取消上级！');
        });
  }
}
